<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use App\Models\Ios;
use App\Models\Taggable;
use App\Models\Topicable;
use App\Models\Ios_type;
use App\Util\Util;
use App\Models\Admin;

class IosController extends BaseController{
    public function getIndex(){
        $typearr=Ios_type::where('status_at',1)->get()->toArray();
        $util=new Util;
        $arr= $util->getTypeTreeview($typearr);
         $adminlist=Admin::where('status_at',1)->select('id','username')->get();
        return view('ios.index')->with('jsontv',json_encode($arr))->with('adminlist',$adminlist);
    }
    
    //返回DataTable
    public function getDatatable(){
        $dt=array();
        $orderby = isset( $_GET[ 'order'  ] ) ? $_GET[ 'columns' ][ $_GET[ 'order' ][ 0 ][ 'column' ] ][ 'name' ] : 'ios.created_at';
        $orderdir = isset( $_GET[ 'order'  ] ) ? $_GET[ 'order' ][ 0 ][ 'dir' ] : 'asc';
        $start = Input::get('start',0);//从多少开始
        $length = Input::get('length',10);//数据长度
        $gettitle=Input::get('search_title');
        $gettypeid=Input::get('search_typeid',0);
        $getssort=Input::get('search_ssort');
        $getstatusat=Input::get('search_statusat');
        $getusername=Input::get('search_username');
        $whereraw='1=1';
        $whereraw.=$gettitle==''?'':' and xz_ios.title like "%'.$gettitle.'%"';
        $whereraw.=$gettypeid>0?' and xz_ios.type_id = '.$gettypeid:'';
        $whereraw.=$getusername>0?' and xz_ios.admin_id = '.$getusername:'';
        switch ($getssort) {
            case 'sort':
                $whereraw.=' and xz_ios.sort = 1';
                break;
            case 'pre':
                $whereraw.=' and xz_ios.pre = 1';
                break;
            case 'comuse':
                $whereraw.=' and xz_ios.comuse = 1';
                break;
            case 'ishot':
                $whereraw.=' and xz_ios.ishot = 1';
                break;
            default:
                # code...
                break;
        }
        if($getstatusat!=''){
            if($getstatusat==1){
                $whereraw.=' and xz_ios.status_at=1';
            }else{
                $whereraw.=' and xz_ios.status_at=0';
            }
        }
        $recordsTotal = Ios::with('ios_type','admin')->count();
        $data = Ios::with('ios_type','admin')
        ->whereRaw($whereraw)
        ->skip($start)->take($length)->orderBy($orderby,$orderdir)->get();
        $recordsFiltered=  Ios::with('ios_type','admin')
        ->whereRaw($whereraw)
        ->count();
        $datatable=array();
        $iseditstr='';
        $isdelstr='';
        if (\Gate::check('chkaccess', 'App\Http\Controllers\IOSController@getEdit')) {
            $iseditstr='<button class="btn-white btn btn-xs" onclick="location.href=\'/ios/edit/$reeditstr\'">编辑</button>';
        }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\IOSController@postDel')) {
            $isdelstr='<button class="btn-white btn btn-xs" onclick="singledel(\'/ios/del\',$redelstr);">删除</button>';
        }
        foreach ($data as $item) {
            $status_at=$item->status_at==1?'<span class="label label-primary">启用</span>':'<span class="label label-danger">禁用</span>';
            $obj=array('<input type="checkbox" name="chk" value='.$item->id.' />',$item->id,'<a class="btn-outline" target="_blank" href="'.config('site.siteurl').'/ios'.$item->id.'">'.$item->title.'</a>',$item->ios_type->name,$item->created_at->format('Y-m-d H:i:s'),$item->updated_at->format('Y-m-d H:i:s'),$item->admin->username,$status_at,str_replace('$reeditstr',$item->id,$iseditstr).str_replace('$redelstr',$item->id,$isdelstr));
            array_push($datatable,$obj);
        }
        $dt['draw']=intval(Input::get('draw',0));
        $dt['data']=$datatable;
        $dt['recordsTotal']=$recordsTotal;
        $dt['recordsFiltered']=$recordsFiltered;
        // $dt['error']='暂时没有数据';
        echo json_encode($dt);     
    }

    public function getAdd(){
        $ptypelist=Ios_type::where('pid',1)->where('status_at',1)->get();
        $topiclist=\DB::select('select id, title,case type_id when 1 then "软件专题" when 2 then "游戏专题" end as typename from xz_topic where type_id < 3 and status_at =1 and deleted_at is null');
        return view('ios.add')->with('ptypelist',$ptypelist)->with('topiclist',$topiclist);
    }

    public function postAdd(){
        \Input::merge(array_map('trim', \Input::except('files','screenshot')));
        $info = new Ios;
        $info->title = Input::get('title');
        $info->subtitle = Input::get('subtitle');
        $info->image = Input::get('image');
        $info->ptype_id = Input::get('ptype_id');
        $info->type_id = Input::get('type_id');
        $info->downurl = Input::get('downurl');
        $info->locdownurl = Input::get('locdownurl');
        $info->qrcode = $this->makeQrcode($info->downurl);
        $info->content = Input::get('content');
        $info->screenshot = implode(',',Input::get('screenshot',array()));
        $info->relkey = Input::get('relkey');
        $info->lang = Input::get('lang');
        $info->filesize = Input::get('filesize');
        $info->authtype = Input::get('authtype');
        $info->tags = Input::get('tags');
        $info->tagkey = Input::get('tagkey');
        $info->platform = Input::get('platform');
        $info->version = Input::get('version');
        $info->pre = Input::get('pre',0);
        $info->comuse = Input::get('comuse',0);
        $info->ishot = Input::get('ishot',0);
        $info->sort = Input::get('sort',0);
        $info->score = Input::get('score',0);
        $info->admin_id = $this->gadmin->id;
        $info->status_at = Input::get('status_at',0);
        // $util=new Util;
        // $info->indexf = strtoupper($util->getFirstCharter($info->title));
        $info->indexf=strtoupper(Input::get('indexf'));
        $res=$info->save();
        $topictype=Input::get('topictype','');
        if($topictype!=''){
            $tapicarr=explode(',',$topictype);
            $insertedId = $info->id;
            foreach ($tapicarr as $key => $value) {
                $topicable=new Topicable;
                $topicable->topic_id=$value;
                $topicable->topicable_id=$insertedId;
                $topicable->topicable_type='App\Models\Ios';
                $topicable->save();
            }
        }
        $tag=Input::get('htag');
        if($tag!=''){
            $tagRelArr=explode(',',$tag);
            $insertedId = $info->id;
            foreach ($tagRelArr as $key => $value) {
                $taggable=new Taggable;
                $taggable->tag_id=$value;
                $taggable->taggable_id=$insertedId;
                $taggable->taggable_type='App\Models\Ios';
                $taggable->save();
            }
        }
        if($res){
            return redirect('tooltip/success')->with(['redirectway'=>'添加成功！','redirecturl'=>'/ios/index']);
        }else{
            return redirect('tooltip/failure')->with(['redirectway'=>'添加失败！','redirecturl'=>'/ios/index']);
        }
    }
    
    public function getEdit($id){
        $info=Ios::find($id);
        $tags = Ios::find($id)->tag;
        $ptypelist=Ios_type::where('pid',1)->where('status_at',1)->get();
        $typelist=Ios_type::where('pid',$info->ptype_id)->get();
        $ssarr=explode(',',$info->screenshot);
        $topiclist=\DB::select('select id, title,case type_id when 1 then "软件专题" when 2 then "游戏专题" end as typename from xz_topic where type_id < 3 and status_at =1 and deleted_at is null');
        $sstopiclist=Topicable::where('topicable_id',$id)->where('topicable_type','App\Models\Ios')->get();
        return view('ios.edit')->with(['info'=>$info,'ptypelist'=>$ptypelist,'typelist'=>$typelist,'ssarr'=>$ssarr,'topiclist'=>$topiclist,'sstopiclist'=>$sstopiclist,'tags'=>$tags]);
    }

    public function postEdit(){
        \Input::merge(array_map('trim', \Input::except('files','screenshot')));
        $id=Input::get('id');
        $info = Ios::find($id);
        $info->title = Input::get('title');
        $info->subtitle = Input::get('subtitle');
        $info->image = Input::get('image');
        $info->ptype_id = Input::get('ptype_id');
        $info->type_id = Input::get('type_id');
        $info->downurl = Input::get('downurl');
        $info->locdownurl = Input::get('locdownurl');
        $info->qrcode = $this->makeQrcode($info->downurl);
        $info->content = Input::get('content');
        $info->screenshot = implode(',',Input::get('screenshot',array()));
        $info->relkey = Input::get('relkey');
        $info->lang = Input::get('lang');
        $info->filesize = Input::get('filesize');
        $info->authtype = Input::get('authtype');
        $info->tags = Input::get('tags');
        $info->tagkey = Input::get('tagkey');
        $info->platform = Input::get('platform');
        $info->version = Input::get('version');
        $info->pre = Input::get('pre',0);
        $info->comuse = Input::get('comuse',0);
        $info->ishot = Input::get('ishot',0);
        $info->sort = Input::get('sort',0);
        $info->score = Input::get('score',0);
        $info->status_at = Input::get('status_at',0);
        // $util=new Util;
        // $info->indexf = strtoupper($util->getFirstCharter($info->title));
        $info->indexf=strtoupper(Input::get('indexf'));
        $res=$info->save();
        Topicable::where('topicable_type','App\Models\Ios')->where('topicable_id',$id)->delete();
        $topictype=Input::get('topictype','');
        if($topictype!=''){
            $topicarr=explode(',',$topictype);
            foreach ($topicarr as $key => $value) {
                $topicable=new Topicable;
                $topicable->topic_id=$value;
                $topicable->topicable_id=$id;
                $topicable->topicable_type='App\Models\Ios';
                $topicable->save();
            }
        }
        Taggable::where('taggable_type','App\Models\Ios')->where('taggable_id',$id)->delete();
        $tag=Input::get('htag');
        if($tag!=''){
            $tagRelArr=explode(',',$tag);
            $insertedId = $info->id;
            foreach ($tagRelArr as $key => $value) {
                $taggable=new Taggable;
                $taggable->tag_id=$value;
                $taggable->taggable_id=$insertedId;
                $taggable->taggable_type='App\Models\Ios';
                $taggable->save();
            }
        }
        if($res){
            return redirect('tooltip/success')->with(['redirectway'=>'编辑成功！','redirecturl'=>'/ios/index']);
        }else{
            return redirect('tooltip/failure')->with(['redirectway'=>'编辑失败！','redirecturl'=>'/ios/index']);
        }
    }

    public function postDel(){
        $data=Input::get('data');
        $res=Ios::destroy($data);
        Topicable::where('topicable_type','App\Models\Ios')->whereIn('topicable_id',$data)->delete();
        Taggable::where('taggable_type','App\Models\Ios')->whereIn('taggable_id',$data)->delete();
        if($res){
            die('1');
        }
        else{
            die('0');
        }
    }
    public function postStatus(){
        $data=Input::get('data');
        $res=Ios::whereIn('id',$data)->update(['status_at' => 1]);;
        if($res){
            die('1');
        }
        else{
            die('0');
        }
    }
    public function getTypeindex(){
        $arr=Ios_type::get()->toArray();
        $isaddstr='';
        $iseditstr='';
        $isdelstr='';
        $issettypestr='';
        if (\Gate::check('chkaccess', 'App\Http\Controllers\IosController@getTypeadd')) {
            $isaddstr='<button class="btn-white btn btn-xs" onclick="location.href=\'/ios/typeadd/$readdstr\'">添加子节点</button>';
        }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\IosController@getTypeedit')) {
            $iseditstr='<button class="btn-white btn btn-xs" onclick="location.href=\'/ios/typeedit/$reeditstr\'">编辑</button>';
        }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\IosController@postTypedel')) {
            $isdelstr='<button class="btn-white btn btn-xs" onclick="singledel(\'/ios/typedel\',$redelstr);">删除</button>';
        }
        $util=new Util;
        $arrt=$util->getTreeview($arr,0,array('isaddstr'=>$isaddstr,'iseditstr'=>$iseditstr,'isdelstr'=>$isdelstr));
        $jsontv=json_encode($arrt);
        return view('ios.typeindex')->with('jsontv',$jsontv);
    }

    public function getTypelist(){
        $data=Input::get('data');
        $list=collect();
        if($data>0){
            $list=Ios_type::where('pid',$data)->get()->toJson();
        }
        die($list);
    }

    public function getTypeadd($pid){
        $ptype=Ios_type::find($pid);
        return view('ios.typeadd')->with('ptype',$ptype);
    }

    public function postTypeadd(){
        $info = new Ios_type;
        $info->name = Input::get('name');
        $info->pid = Input::get('pid');
        $info->sort = Input::get('sort',0);
        $info->status_at = Input::get('status_at',0);
        $res=$info->save();
        if($res){
            return redirect('tooltip/success')->with(['redirectway'=>'添加成功！','redirecturl'=>'/ios/typeindex']);
        }else{
            return redirect('tooltip/failure')->with(['redirectway'=>'添加失败！','redirecturl'=>'/ios/typeindex']);
        }
    }
    
    public function getTypeedit($id){
        $info=Ios_type::with('pios_type')->find($id);
        return view('ios.typeedit')->with('info',$info);
    }

    public function postTypeedit(){
        $id=Input::get('id');
        $info = Ios_type::find($id);
        $info->name = Input::get('name');
        $info->sort = Input::get('sort',0);
        $info->status_at = Input::get('status_at',0);
        $res=$info->save();
        if($res){
            return redirect('tooltip/success')->with(['redirectway'=>'编辑成功！','redirecturl'=>'/ios/typeindex']);
        }else{
            return redirect('tooltip/failure')->with(['redirectway'=>'编辑失败！','redirecturl'=>'/ios/typeindex']);;
        }
        
    }

    public function postTypedel(){
        // $data=Input::get('data');
        // Ios_type::destroy($data);
        // Ios::where('ptype_id',$data)->delete();
        // Ios::where('type_id',$data)->delete();
        // $ios_type=Ios_type::all();
        // $this->redel($ios_type,$data);
        // die('1');
        $data=Input::get('data')[0];
        Ios_type::destroy($data);
        $ableid= \DB::table('ios')->where('ptype_id',$data)->orWhere('type_id',$data)->lists('id');
        Taggable::where('taggable_type','App\Models\Ios')->whereIn('taggable_id',$ableid)->delete();
        Topicable::where('topicable_type','App\Models\Ios')->whereIn('topicable_id',$ableid)->delete();
        Ios::where('ptype_id',$data)->orWhere('type_id',$data)->delete();
        Ios_type::where('pid',$data)->delete();
        die('1');
    }

    // private function redel($data,$id){
    //     foreach ($data as $key => $value) {
    //         if($value->pid==$id){
    //             Ios_type::where('pid',$id)->delete();
    //             Ios::where('type_id',$id)->delete();
    //             $this->redel($data,$value->id);
    //         }
    //     }
    // }

     public function postUploadimg(){
        if (Input::hasFile('file'))
        {
            $file=Input::file('file');
            if($file -> isValid()){
                $folder='uploads/file/'.date('Ymd');
                if(!file_exists($folder)){
                 mkdir($folder);
                }
                $clientName = $file -> getClientOriginalName();
                // $tmpName = $file->getFileName(); // 缓存在tmp文件夹中的文件名 例如 php8933.tmp 这种类型的.
                // $realPath = $file->getRealPath();    //这个表示的是缓存在tmp文件夹下的文件的绝对路径
                $extension = $file -> getClientOriginalExtension(); //上传文件的后缀.
                // $mimeTye = $file -> getMimeType();//开启php的extension=php_fileinfo.dll
                // $newName = time().$clientName;
                $newName = time().rand(1000, 9999).'.'.$extension;
                // $file -> move($folder,$newName);
                \Image::make($file)->resize(150, 150)->save($folder.'/'.$newName);
                $path='/'.$folder.'/'.$newName;
                // $file->move('uploads');
                $data['file']=array();
                $subdata['name']=$clientName;
                // $subdata['size']=$mimeTye;
                $subdata['url']=$path;
                $data['file'][]=$subdata;
                die(json_encode($data));
            }
        }
    }

    public function postUploadqr(){
        if (Input::hasFile('file'))
        {
            $file=Input::file('file');
            if($file -> isValid()){
                $folder='uploads/file/'.date('Ymd');
                if(!file_exists($folder)){
                 mkdir($folder);
                }
                $clientName = $file -> getClientOriginalName();
                // $tmpName = $file->getFileName(); // 缓存在tmp文件夹中的文件名 例如 php8933.tmp 这种类型的.
                // $realPath = $file->getRealPath();    //这个表示的是缓存在tmp文件夹下的文件的绝对路径
                $extension = $file -> getClientOriginalExtension(); //上传文件的后缀.
                // $mimeTye = $file -> getMimeType();//开启php的extension=php_fileinfo.dll
                // $newName = time().$clientName;
                $newName = time().rand(1000, 9999).'.'.$extension;
                // $file -> move($folder,$newName);
                \Image::make($file)->resize(120, 120)->save($folder.'/'.$newName);
                $path='/'.$folder.'/'.$newName;
                // $file->move('uploads');
                $data['file']=array();
                $subdata['name']=$clientName;
                // $subdata['size']=$mimeTye;
                $subdata['url']=$path;
                $data['file'][]=$subdata;
                die(json_encode($data));
            }
        }
    }

    public function postUpload(){
        if (Input::hasFile('file'))
        {
            $file=Input::file('file');
            if($file -> isValid()){
                $folder='uploads/file/'.date('Ymd');
                if(!file_exists($folder)){
                 mkdir($folder);
                }
                $clientName = $file -> getClientOriginalName();
                // $tmpName = $file->getFileName(); // 缓存在tmp文件夹中的文件名 例如 php8933.tmp 这种类型的.
                // $realPath = $file->getRealPath();    //这个表示的是缓存在tmp文件夹下的文件的绝对路径
                $extension = $file -> getClientOriginalExtension(); //上传文件的后缀.
                // $mimeTye = $file -> getMimeType();//开启php的extension=php_fileinfo.dll
                // $newName = time().$clientName;
                $newName = time().rand(1000, 9999).'.'.$extension;
                $file -> move($folder,$newName);
                // \Image::make($file)->resize(300, 200)->save($folder.'/'.$newName);
                $path='/'.$folder.'/'.$newName;
                // $file->move('uploads');
                $data['file']=array();
                $subdata['name']=$clientName;
                // $subdata['size']=$mimeTye;
                $subdata['url']=$path;
                $data['file'][]=$subdata;
                die(json_encode($data));
            }
        }
   }

   public function postUploadss(){
        if (Input::hasFile('files')){
            $files=Input::file('files');
            $data['file']=array();
            foreach($files as $file) {
                if($file -> isValid()){
                    $folder='uploads/file/'.date('Ymd');
                    if(!file_exists($folder)){
                     mkdir($folder);
                    }
                    $clientName = $file -> getClientOriginalName();
                    $extension = $file -> getClientOriginalExtension(); //上传文件的后缀.
                    $newName = time().rand(1000, 9999).'.'.$extension;
                    $file -> move($folder,$newName);
                    // \Image::make($file)->resize(300, 200)->save($folder.'/'.$newName);
                    $path='/'.$folder.'/'.$newName;
                    $subdata['name']=$clientName;
                    $subdata['url']=$path;
                    // $data['file'][]=$subdata;
                    array_push($data['file'],$subdata);
                }
            }
            die(json_encode($data));
            
        }
    }

    //生成二维码
    private function makeQrcode($qrtxt){
        $folder='uploads/file/'.date('Ymd').'/';
        if(!file_exists($folder)){
            mkdir($folder);
        }
        $newName = time().rand(1000, 9999).'.jpg';
        $newfolder=$folder.$newName;
        file_put_contents($newfolder,file_get_contents(action('HelperController@getQrcode').'?qrtxt='.$qrtxt));
        return '/'.$newfolder;
    }
}
